package com.yumi.controller;


import com.yumi.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Tag(name = "文件处理", description = "文件压缩与下载相关接口")
@RestController
@Slf4j
@RequestMapping("/tem")
public class TemController {

    /**
     * 文件压缩并下载
     * @param file 待压缩的上传文件
     * @return 压缩结果信息
     */
    @Operation(summary = "文件压缩并下载", description = "将上传的文件压缩为ZIP格式并保存到桌面")
    @PostMapping
    public Result download(@RequestParam("file") MultipartFile file) {
        log.info("接收上传文件: {}", file.getOriginalFilename());
        
        // 文件验证
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }
        
        if (file.getSize() > 10 * 1024 * 1024) {
            return Result.error("上传文件大小不能超过10MB");
        }
        
        // 获取桌面路径
        String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
        File desktopDir = new File(desktopPath);
        if (!desktopDir.exists()) {
            return Result.error("无法找到桌面路径");
        }
        
        // 准备压缩文件信息
        String originalFileName = file.getOriginalFilename();
        String zipFileName = originalFileName.substring(0, originalFileName.lastIndexOf('.')) + ".zip";
        String zipFilePath = desktopPath + File.separator + zipFileName;
        
        // 执行压缩操作
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
             InputStream in = file.getInputStream()) {
            
            // 添加文件到压缩包
            ZipEntry zipEntry = new ZipEntry(originalFileName);
            try {
                zos.putNextEntry(zipEntry);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 写入文件内容
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            
            return Result.success("文件已压缩并保存到桌面: " + zipFileName);
        } catch (IOException e) {
            log.error("文件压缩或保存失败", e);
            return Result.error("文件处理失败: " + e.getMessage());
        }
    }
}